/**
 * 
 */
package cn.antia.cep.busi;

import java.util.Date;
import java.util.List;

import cn.antia.cep.common.AntiaLog;
import cn.antia.cep.common.DBFlag;
import cn.antia.cep.common.Privilege;
import cn.antia.cep.common.SampleEncryption;
import cn.antia.cep.db.hibernate.bean.Role;
import cn.antia.cep.db.hibernate.bean.User;
import cn.antia.cep.db.hibernate.bean.VisitLog;

/**
 * @author xiao
 * @date Feb 23, 2008
 * @time 7:07:14 PM
 */
public class LoginService extends DbHibernateService {
	/**
	 * 登录
	 * @param nickname
	 * @param password
	 * @param log
	 * @return
	 */
	public Privilege login(String nickname,String password,VisitLog log) {
		Privilege p = new Privilege();
		password = SampleEncryption.getEncryptString(password);
		String hql = new StringBuilder("from User where valid = 1 and nickname = '").append(nickname).append("' and password = '").append(password).append("'").toString();
		List userlist = find(hql);
		// 登录失败
		if (userlist == null || userlist.size() < 1) {
			AntiaLog.info(new StringBuffer("用户").append(nickname).append("登录失败！用户名或密码不正确.").toString());
			return null;
		} else if (userlist.size() == 1) {
			AntiaLog.info(new StringBuffer("用户").append(nickname).append("登录成功！").toString());
			/** 设置管理员信息，保存的管理员对象中包含权限信息 */
			User user = (User) userlist.get(0);
			p.setUser(user);
			// 取出角色信息
			hql = "from Role where id in(select roleId from UserRole where userId = " + user.getId() + ")";
			List roles = find(hql);
			// 保存最后登录时间与登录次数（更新到数据库）
			Date now = new Date();
			p.setRoles(roles);
			p.setLoginTime(now);
			//用户资料修改
			user.setLastLogonTime(now);
			user.setLogonTimes(user.getLogonTimes() + 1);
			update(user);
			
			boolean hasRight = false;
            for (Object role1 : roles) {
                Role role = (Role) role1;
                if (role.getId() == DBFlag.ROLE_SUPER_MANAGER
                        || role.getId() == DBFlag.ROLE_NORMAL_MANAGER) {
                    hasRight = true;
                    break;
                }
            }
            log.setUsername(user.getNickname());
			log.setUserId(user.getId());
			log.setUserType(DBFlag.VISIT_LOG_USER_REGISTERED);
			log.setLoginType(hasRight ? DBFlag.VISIT_LOG_LOGIN_ADMIN : DBFlag.VISIT_LOG_LOGIN_GENE);
			log.setUsername(user.getNickname());
			log.setUserId(user.getId());
			update(log);
		}
		return p;
	}

}
